<template>
  <el-dialog
      :title="isEdit ? '编辑行程库' : (isDetail ? '行程库详情' : '新增行程库')"
      width="900px"
      v-model="visible"
      :close-on-click-modal="false"
      @close="handleDialogClose"
  >
    <!-- 行程库名称和返回按钮同一行 -->
    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px;">
      <el-form-item label="行程库名称" style="margin: 0;">
        <el-input

            v-model="form.itineraryName"
            placeholder="请输入行程库名称"
            :disabled="isDetail"
            style="width: 100%;"
        />
      </el-form-item>
      <el-button type="primary" @click="handleBack">返回</el-button>
    </div>

    <!-- 内容块 -->
    <div
        v-for="(content, index) in contentList"
        :key="index"
        class="content-block"
    >
      <div class="content-header">
        <span>内容{{ index + 1 }}</span>
        <el-button
            type="primary"
            text
            icon="delete"
            @click="handleDeleteContent(index)"
            :disabled="isDetail || contentList.length <= 1"
        >
          删除内容
        </el-button>
      </div>

      <el-form-item label="时长" style="display: flex; align-items: center; margin: 0;">
        <el-input
            v-model.number="content.traDuringNumber"
            placeholder="请输入时长"
            :disabled="isDetail"
            type="number"
            min="1"
            style="flex: 1; margin-right: 8px; width: 20%"
        />
        <el-select
            v-model="content.traDuringUnit"
            placeholder="请选择单位"
            :disabled="isDetail"
            style="width: 20%;"
        >
          <el-option label="天" value="day"></el-option>
          <el-option label="小时" value="hour"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="内容描述">
        <el-input
            type="textarea"
            v-model="content.content"
            placeholder="请输入内容描述"
            :disabled="isDetail"
            rows="3"
        />
      </el-form-item>

      <!-- 图片上传（限制3张） -->
      <el-form-item label="图片上传">
        <el-upload
            class="image-upload"
            :action="uploadUrl"
            :file-list="content.images"
            :limit="3"
            :on-preview="handlePreview"
            :on-remove="(file, fileList) => handleRemove(file, fileList, index)"
            :on-exceed="handleExceed"
            :on-success="(response, file, fileList) => handleUploadSuccess(response, file, fileList, index)"
            list-type="picture-card"
            :disabled="isDetail"
        >
          <div slot="default">点击上传图片</div>
        </el-upload>
        <div class="upload-tip">图片上传限制3张以内</div>
      </el-form-item>
    </div>

    <!-- 添加内容按钮 -->
    <el-button
        type="primary"
        text
        icon="plus"
        @click="handleAddContent"
        style="margin-top: 10px"
        :disabled="isDetail"
    >
      添加内容
    </el-button>

    <!-- 底部按钮 -->
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button
          type="primary"
          @click="handleSave"
          :disabled="isDetail"
      >
        {{ isEdit ? '更新' : '保存' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import type { UploadFile, UploadProps } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addItineraryWithContent } from '/@/api/itinerary/itinerary';
import { selectItineraryContentByItineraryId } from '/@/api/itinerary/itineraryContent';
import { useRouter } from 'vue-router';

// 路由实例
const router = useRouter();

// 表单状态
const visible = ref(false)
const isEdit = ref(false)    // 区分编辑/新增
const isDetail = ref(false)  // 区分详情模式
const form = reactive({
  itineraryId: '',
  itineraryName: '', // 行程库名称
})

// 内容项接口定义
interface Content {
  traDuringUnit: string
  content: string
  traDuringNumber: number | null
  images: UploadFile[]
  imageUrls?: string[]  // 用于存储上传后的图片URL
}

// 内容块列表
const contentList = reactive<Content[]>([
  { traDuringUnit: '', content: '', traDuringNumber: null, images: [] }
])

// 图片上传相关
const uploadUrl = '/api/upload/image' // 替换为实际上传地址
const handlePreview = (file: UploadFile) => {
  // 预览图片逻辑，可打开新窗口显示
  window.open(file.url as string, '_blank')
}

const handleRemove = (file: UploadFile, fileList: UploadFile[], index: number) => {
  contentList[index].images = fileList;
  // 更新图片URL列表
  updateImageUrls(index);
}

const handleExceed = () => {
  ElMessage.warning('最多只能上传3张图片')
}

// 上传成功处理
const handleUploadSuccess = (response: any, file: UploadFile, fileList: UploadFile[], index: number) => {
  // 假设接口返回格式 { code: 200, data: { url: '图片地址' } }
  if (response.code === 200) {
    file.url = response.data.url;
    contentList[index].images = fileList;
    updateImageUrls(index);
  } else {
    ElMessage.error('图片上传失败: ' + (response.msg || '未知错误'));
  }
}

// 更新图片URL列表
const updateImageUrls = (index: number) => {
  contentList[index].imageUrls = contentList[index].images
      .filter(file => file.url)
      .map(file => file.url as string);
}

// 内容块操作
const handleAddContent = () => {
  contentList.push({ traDuringUnit: '', content: '', traDuringNumber: null, images: [] })
}

const handleDeleteContent = (index: number) => {
  if (contentList.length <= 1) {
    ElMessage.warning('至少保留一个内容块');
    return;
  }

  ElMessageBox.confirm(
      '确定要删除这个内容块吗？',
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    contentList.splice(index, 1);
    ElMessage.success('删除成功');
  }).catch(() => {
    // 取消删除
  });
}

// 表单验证
const validateForm = (): boolean => {
  // 验证行程库名称
  if (!form.itineraryName.trim()) {
    ElMessage.warning('请输入行程库名称');
    return false;
  }

  // 验证每个内容块
  for (let i = 0; i < contentList.length; i++) {
    const content = contentList[i];
    if (content.traDuringNumber === null || !content.traDuringNumber) {
      ElMessage.warning(`请输入内容${i + 1}的时长`);
      return false;
    }
    if (!content.traDuringUnit) {
      ElMessage.warning(`请选择内容${i + 1}的时长单位`);
      return false;
    }
    if (!content.content.trim()) {
      ElMessage.warning(`请输入内容${i + 1}的描述`);
      return false;
    }
  }

  return true;
}

// 保存逻辑
const handleSave = async () => {
  // 表单验证
  if (!validateForm()) {
    return;
  }

  // 准备提交数据
  const submitData = {
    itineraryId: form.itineraryId,
    itineraryName: form.itineraryName,
    trItineraryContents: contentList.map(content => ({
      traDuringNumber: content.traDuringNumber,
      traDuringUnit: content.traDuringUnit,
      content: content.content,
      images: content.imageUrls || []
    }))
  };

  try {
    let result;
    // 根据状态调用不同接口
    if (isEdit.value) {
      await updateItineraryWithContent(submitData);
      ElMessage.success('更新成功');
    } else {
      result = await addItineraryWithContent(submitData);
      // 从返回结果中提取行程库ID（后端返回格式：{code:0, data: "26", ...}）
      const newItineraryId = result.data; // 这里的data就是ID（如"26"）
      console.log("新增行程库成功，ID为：", newItineraryId); // 可用于后续业务逻辑

      ElMessage.success(`新增成功，行程库ID：${newItineraryId}`);
    }

    // 关闭弹窗并触发父组件刷新
    visible.value = false;
    emits('refresh');
  } catch (error: any) {
    ElMessage.error(error.msg || (isEdit.value ? '更新失败' : '添加失败'));
    console.error('保存失败:', error);
  }
}

// 返回逻辑
const handleBack = () => {
  visible.value = false;
}

// 弹窗关闭时重置表单
const handleDialogClose = () => {
  emits('refresh');
  resetForm();
}

// 重置表单
const resetForm = () => {
  form.itineraryId = '';
  form.itineraryName = '';
  contentList.splice(0, contentList.length);
  contentList.push({ traDuringUnit: '', content: '', traDuringNumber: null, images: [] });
  isEdit.value = false;
  isDetail.value = false;
}

// 接收父组件传递的行程数据（用于编辑和详情）
const openDialog = (itineraryId?: string, isDetailState = false) => {
  resetForm();
  isDetail.value = isDetailState;

  if (itineraryId) {
    // 如果有ID，说明是编辑或详情模式
    isEdit.value = !isDetailState;
    form.itineraryId = itineraryId;
    // 这里应该调用接口获取行程详情数据
    // fetchItineraryDetail(itineraryId);
  }

  visible.value = true;
}

// 定义暴露给父组件的方法
defineExpose({
  openDialog
});

// 定义 emits
const emits = defineEmits(['refresh']);
</script>

<style scoped>
/* 内容块样式 */
.content-block {
  border: 1px solid #eee;
  padding: 16px;
  margin-bottom: 16px;
  border-radius: 4px;
}
.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #eee;
}
/* 图片上传样式 */
.image-upload {
  margin-top: 8px;
}
.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}
</style>
